package com.ruoyi.web.service.stock.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.domain.stock.Retrieval;
import com.ruoyi.web.domain.stock.Stock;
import com.ruoyi.web.domain.stock.Storage;
import com.ruoyi.web.mapper.stock.RetrievalMapper;
import com.ruoyi.web.mapper.stock.StockMapper;
import com.ruoyi.web.mapper.stock.StorageMapper;
import com.ruoyi.web.pojo.dto.stock.RetrievalRep;
import com.ruoyi.web.pojo.dto.stock.StockVo;
import com.ruoyi.web.pojo.dto.stock.StorageRep;
import com.ruoyi.web.service.stock.IStockService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zq
 */
@Service
public class StockService implements IStockService {


    private final StockMapper stockMapper;
    private final StorageMapper storageMapper;
    private final RetrievalMapper retrievalMapper;

    public StockService(StockMapper stockMapper, StorageMapper storageMapper,  RetrievalMapper retrievalMapper) {
        this.stockMapper = stockMapper;
        this.storageMapper = storageMapper;
        this.retrievalMapper = retrievalMapper;
    }


    /**
     * 查询库存
     *
     * @param id 库存主键
     * @return 库存
     */
    @Override
    public StockVo selectStockById(String id)
    {
        StockVo stock = stockMapper.selectStockVoById(id);
        if (SecurityUtils.isParkManager()){
            return stock;
        }else if (SecurityUtils.getUserId().equals(stock.getUserId())){
            return stock;
        }else {
            return null;
        }
    }

    /**
     * 查询库存列表
     *
     * @param stock 库存
     * @return 库存
     */
    @Override
    public List<StockVo> selectStockList(Stock stock)
    {
        if (SecurityUtils.isParkManager()){
            stock.setUserId(null);
        }else {
            stock.setUserId(SecurityUtils.getUserId());
        }
        if (stock.getStartTime() != null && stock.getEndTime() != null){
            stock.setStartTime(DateUtils.minDate(stock.getStartTime()));
            stock.setEndTime(DateUtils.maxDate(stock.getEndTime()));
        }

        List<StockVo> stocks = stockMapper.selectStockList(stock);
        if (CollectionUtils.isEmpty(stocks)){
            return new ArrayList<>();
        }
        return stocks;
    }

    /**
     * 新增库存
     *
     * @param stock 库存
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor =  Exception.class)
    public int insertStock(Stock stock)
    {
        stock.setCreateTime(DateUtils.getNowDate());
        stock.setCreateBy(SecurityUtils.getUsername());
        stock.setUpdateTime(DateUtils.getNowDate());
        stock.setUserId(SecurityUtils.getUserId());
        //校验
        checkStock(stock);
        //入库
        insertStorage(stock);
        return stockMapper.insertStock(stock);
    }

    private void checkStock(Stock stock) {
        Stock check = new Stock();
        check.setUserId(stock.getUserId());
        check.setProduct(stock.getProduct());
        check.setType(stock.getType());
        List<Stock> stocks = stockMapper.selectStockListVo(check);
        if (CollectionUtils.isNotEmpty(stocks)){
            throw new ServiceException("该产品已存在");
        }
    }

    private void insertStorage(Stock stock) {
        Storage storage = Storage.builder().stockId(stock.getId())
                .userId(stock.getUserId()).type(stock.getType())
                .product(stock.getProduct()).unit(stock.getUnit())
                .number(stock.getNumber()).build();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String s = objectMapper.writeValueAsString(storage);
            storage.setRemark(s);
            storage.setCreateBy(SecurityUtils.getUsername());
            storage.setCreateTime(DateUtils.getNowDate());
            storageMapper.insertStorage(storage);
        } catch (JsonProcessingException e) {
            throw new ServiceException("入库失败");
        }

    }

    /**
     * 修改库存
     *
     * @param stock 库存
     * @return 结果
     */
    @Override
    public int updateStock(Stock stock)
    {
        stock.setUpdateTime(DateUtils.getNowDate());
        stock.setUpdateBy(SecurityUtils.getUsername());
        return stockMapper.updateStock(stock);
    }



    /**
     * 删除库存信息
     *
     * @param id 库存主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteStockById(String id)
    {
        //Stock stock = stockMapper.selectStockById(id);
        //删除入库
        deleteStorage(id);
        //删除出库
        deleteRetrieval(id);
        return stockMapper.deleteStockById(id);
    }

    private void deleteRetrieval(String id) {
        Retrieval retrieval = new Retrieval();
        retrieval.setStockId(id);
        List<RetrievalRep> retrievals = retrievalMapper.selectRetrievalList(retrieval);
        retrievalMapper.deleteRetrievalByIds(retrievals.stream().map(RetrievalRep::getId).collect(Collectors.toList()));
    }

    private void deleteStorage(String id) {
        Storage storage = new Storage();
        storage.setStockId(id);
        List<StorageRep> storages = storageMapper.selectStorageList(storage);
        storageMapper.deleteStorageByIds(storages.stream().map(StorageRep::getId).collect(Collectors.toList()));
    }
}
